package ch.zbw.timeline.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ch.zbw.timeline.domain.Employee;
import ch.zbw.timeline.domain.LogEntry;
import ch.zbw.timeline.domain.LogType;
import ch.zbw.timeline.repository.EmployeeRepository;
import ch.zbw.timeline.repository.LogEntryRepository;
import ch.zbw.timeline.repository.hibernate.HibernateEmployeeRepository;
import ch.zbw.timeline.repository.hibernate.HibernateLogEntryRepository;

/**
 * Interface that handles the logEntries They are created and saved to the
 * database. They can be read from the database.
 * 
 * @author Marco Ramseyer
 * @version 25.12.2011
 * 
 */
public class ZbwLogService implements LogService {

	LogEntryRepository logRepository;

	/**
	 * Default constructor without parameters initiates the logRepository
	 */
	public ZbwLogService() {
		// logRepository = new MockLogRepository();
		logRepository = new HibernateLogEntryRepository();
	}

	/**
	 * Constructur with parameters initiates a new logRepository
	 * 
	 * @param logRepository
	 */
	public ZbwLogService(LogEntryRepository logRepository) {
		this.logRepository = logRepository;
	}

	/*
	 * (non-Javadoc)
	 * @see ch.zbw.timeline.service.LogService#addLogEntry(ch.zbw.timeline.domain.LogType, ch.zbw.timeline.domain.Employee, java.lang.String)
	 */
	@Override
	public LogEntry addLogEntry(LogType logType, Employee employee,
			String description) {

		LogEntry logEntry = new LogEntry();
		logEntry.setLogTypeString(logType.toString());
		logEntry.setLogType(logType);
		logEntry.setEmployee(employee);
		logEntry.setEmployeeFk(employee.getId());
		logEntry.setDescription(description);
		logEntry.setRegistredOn(new Timestamp(System.currentTimeMillis() + 3600000));
		
		return logRepository.addLogEntry(logEntry);
	}

	/*
	 * (non-Javadoc)
	 * @see ch.zbw.timeline.service.LogService#getAllLogEntries()
	 */
	@Override
	public List<LogEntry> getAllLogEntries() {
		EmployeeRepository employeeRepository = new HibernateEmployeeRepository();
		List<LogEntry> logEntries = logRepository.getAllLogEntries();
		List<LogEntry> tempLog = new ArrayList<LogEntry>();
		
		for(LogEntry l: logEntries){
			if(l.getEmployeeFk() != null){
				l.setEmployee(employeeRepository.getEmployeeById(l.getEmployeeFk()));				
			}
			else{
				l.setEmployee(null);
			}
			tempLog.add(l);
		}
				
		return tempLog;
	}

}
